/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 拼多多投诉工单详情，操作表单
 *  */
import React, { useEffect, useState } from 'react';
import { Drawer, Steps, Button, Form, message, Typography, notification } from 'antd';
import KbImage from '@/components/KbImage';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProForm, {
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormUploadButton,
  ProFormDigit,
  ProFormDependency,
} from '@ant-design/pro-form';
import { connect, useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { Dispatch } from 'umi';
import type { Rule } from 'antd/lib/form';
import type {
  PddComplaintDeatil,
  PddComplaintTypes,
  RecordDetail,
} from '../types/PDDComplaintOrder';

interface ModalProps {
  detail: PddComplaintDeatil;
  loadingDetail: boolean | undefined;
  dispatch: Dispatch;
  id?: string;
  visible: boolean;
  type: 'todo' | 'secondComplaint' | 'finished';
  triggleVisible: (open: boolean) => void;
  pddComplaintTypes: PddComplaintTypes;
  reloadTable: () => void | undefined;
  page_ids: string[] | undefined[];
  submitLoading: boolean | undefined;
  activeKey: 'todo' | 'secondComplaint' | 'finished' | string;
}

const tailLayout = {
  labelCol: { span: 6, offest: 8 },
  wrapperCol: { span: 18 },
};
const { Step } = Steps;
const { Title } = Typography;
notification.config({
  top: 80,
  duration: 3,
  placement: 'topRight',
});

const HandlingDrawerForm: React.FC<ModalProps> = (props) => {
  const {
    visible,
    triggleVisible,
    type,
    id,
    dispatch,
    detail,
    pddComplaintTypes,
    reloadTable,
    page_ids = [],
    submitLoading,
  } = props;
  const { complaint, pdd_gd, inn, record = [] } = detail;
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [imgList, setImgList] = useState<any[]>([]);
  const [detailId, setDetailId] = useState<string | undefined>(id);
  const [nextId, setNextId] = useState<string | undefined>(undefined);
  const [prevId, setPrevId] = useState<string | undefined>(undefined);
  const [status, setStatus] = useState(complaint?.is_deal);
  const [disableSubmit, setDisableSubmit] = useState(false);
  const [form] = Form.useForm();

  const getDetail = (id_: string | undefined) => {
    dispatch({
      type: 'pddComplaint/getPddDetail',
      payload: {
        id: id_,
      },
    });
  };

  const onDropdownVisibleChange = (isVisible: boolean) => {
    if (!isVisible) return;
    dispatch({
      type: 'pddComplaint/getComplaintTypeInfo',
      payload: {
        id: detail?.complaint?.complaint_type,
      },
    });
  };

  useEffect(() => {
    setStatus(detail?.complaint?.is_deal);
  }, [detail]);

  useEffect(() => {
    const nextId_ = page_ids[page_ids.indexOf(id as never) + 1];
    const prevId_ = page_ids[page_ids.indexOf(id as never) - 1];

    setNextId(nextId_);
    setPrevId(prevId_);

    setDetailId(id);
  }, [id, page_ids]);

  useEffect(() => {
    if (detailId) {
      getDetail(detailId);
    }
  }, [detailId]);

  useEffect(() => {
    form.setFieldsValue({
      reason: complaint?.complaint_type_text,
    });
  }, [complaint]);

  useEffect(() => {
    if (!visible) {
      form.resetFields();
    }
  }, [visible, form]);

  const onValuesChange = (changedValues: any) => {
    if (changedValues?.compensation) {
      form.setFieldsValue({
        compensationMoney: 0,
      });
    }
  };

  const onClose = () => {
    form.resetFields();
    setImgList([]);
    triggleVisible(false);
    setDisableSubmit(false);
  };

  const passRecordToPDD = (record_id: any) => {
    dispatch({
      type: 'pddComplaint/passRecordToPDD',
      payload: {
        record_id,
      },
    }).then(() => {
      getDetail(detailId);
      notification.success({
        message: '提交成功，已提交给拼多多。',
      });
    });
  };

  const onPreview = async (file: any) => {
    let src = file.url || file.src;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  const beforeUpload = (fileParams: any) => {
    const file = fileParams;
    const isJpgOrPng =
      file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJpgOrPng) {
      message.error('只能上传 JPEG/JPG/PNG 格式的图片');
      return false;
    }
    const isLt600KB = file.size / 1024 < 600;
    if (!isLt600KB) {
      message.error('单张图片大小不能超过600KB');
      return false;
    }
    // 显示缩略图
    const r = new FileReader();
    r.readAsDataURL(file);
    r.onload = (e) => {
      file.thumbUrl = e.target?.result;
      file.src = e.target?.result; // 图片预览地址
      setImgList((prevList) => [...prevList, file]);
    };
    return false;
  };

  const onRemove = (file: any) => {
    setImgList((prevList) => {
      const index = prevList.indexOf(file);
      const newFileList = prevList.slice();
      newFileList.splice(index, 1);
      return newFileList;
    });
  };

  const onReset = () => {
    setImgList([]);
  };

  const onSubmit = async (values: any) => {
    const formData = new FormData();
    const { id: complaintId } = complaint;
    const needPay = pddComplaintTypes[values.select] === '包裹丢失';
    imgList.forEach((val, index) => {
      formData.append(`img_${index + 1}`, val);
    });

    const payload = {
      id: complaintId,
      act_info: values.select,
      act_money: values.compensationMoney * 100 || 0,
      act_compensate: needPay ? values.compensation : 0,
      act_desc: values.remark,
      waybill_no: complaint.waybill_no,
    };

    Object.keys(payload).forEach((key) => {
      formData.append(key, payload[key]);
    });

    dispatch({
      type: 'pddComplaint/pddComplaintSubmit',
      payload: formData,
    }).then(() => {
      setDisableSubmit(true);
      if (pddComplaintTypes[values.select] === '处理中') {
        notification.success({
          message: '保存成功，未提交给拼多多。',
        });
      } else {
        notification.success({
          message: '提交成功，已提交给拼多多。',
        });
      }
      // onClose()
      getDetail(detailId);
      form.resetFields();
      setImgList([]);
      if (reloadTable) {
        reloadTable();
      }
    });
  };

  useEffect(() => {
    const nextId_ = page_ids[page_ids.indexOf(detailId as never) + 1];
    const prevId_ = page_ids[page_ids.indexOf(detailId as never) - 1];

    setPrevId(prevId_);
    setNextId(nextId_);
  }, [detailId, page_ids]);

  const onNextOrPrevClick = (next_prev: string) => {
    const nextId_ = page_ids[page_ids.indexOf(detailId as never) + 1];
    const prevId_ = page_ids[page_ids.indexOf(detailId as never) - 1];
    setDisableSubmit(false);
    setImgList([]);
    form.resetFields();
    form.setFieldsValue({
      files: [],
    });
    if (next_prev === 'next') {
      setDetailId(nextId_);
    } else {
      setDetailId(prevId_);
    }
  };

  return (
    <Drawer
      title='拼多多投诉工单'
      width={winSize === 'xs' ? 300 : 700}
      visible={visible}
      onClose={onClose}
      getContainer={false}
    >
      <div style={{ paddingBottom: 60 }}>
        <Typography style={{ marginBottom: 30 }}>
          <Title level={3}>工单详情</Title>
          <ProDescriptions
            title='工单信息'
            dataSource={{ ...complaint, ...pdd_gd }}
            columns={[
              {
                title: '工单号',
                dataIndex: 'ticket_id',
              },
              {
                title: '运单号',
                dataIndex: 'waybill_no',
              },
              {
                title: '投诉时间',
                dataIndex: 'create_at',
              },
            ]}
          />
          <ProDescriptions
            title='客户信息'
            dataSource={pdd_gd}
            columns={[
              {
                title: '客户姓名',
                dataIndex: 'receive_name',
              },
              {
                title: '客户联系方式',
                dataIndex: 'receive_contact',
              },
            ]}
          />
          <ProDescriptions
            title='被投诉驿站'
            dataSource={inn}
            columns={[
              {
                title: '驿站名称',
                dataIndex: 'inn_name',
              },
              {
                title: '驿站手机号',
                dataIndex: 'phone',
              },
            ]}
          />
          <ProDescriptions
            title='投诉详情'
            dataSource={complaint}
            column={1}
            columns={[
              {
                title: '投诉原因',
                dataIndex: 'complaint_type_text',
              },
              {
                title: '问题描述',
                dataIndex: 'complaint_desc',
              },
              // {
              //   title: '申诉理由',
              //   dataIndex: 'complaint_desc', // 待定
              // },
            ]}
          />
        </Typography>
        {record.length > 0 ? (
          <Typography style={{ marginBottom: 30 }}>
            <Title level={3}>处理记录</Title>
            <Steps progressDot current={record.length - 1} direction='vertical'>
              {record.map((val: RecordDetail) => {
                const {
                  act_info: {
                    act_desc,
                    act_img,
                    act_info,
                    act_money,
                    act_name,
                    act_source,
                    act_status,
                    act_status_text,
                    act_tel,
                  } = {},
                } = val;
                const needPay = act_info === '包裹丢失';
                const isYZ = act_source === '驿站';
                const finished = act_status == '1';
                const showSendToPDDBtn =
                  type !== 'finished' &&
                  (status == '2' || status == '3') &&
                  act_info !== '处理中' &&
                  act_status == '3';
                return (
                  <Step
                    key={val.id}
                    title={val.create_time}
                    description={
                      <>
                        <div style={{ marginBottom: 10 }}>
                          {`${act_source} ${act_name} ${isYZ ? '' : `（${act_tel}）`} ${
                            finished ? act_status_text : ''
                          }`}
                        </div>
                        <div style={{ marginBottom: 10 }}>
                          {`【处理结果】${act_info} ${
                            needPay
                              ? act_money == '0'
                                ? '无需赔偿'
                                : `，已赔付${Number(act_money) / 100}元`
                              : ''
                          }`}
                        </div>
                        <div style={{ marginBottom: 10 }}>{`【处理详情】${act_desc}`}</div>
                        {act_img?.map((item: string | undefined) => (
                          <div style={{ display: 'inline-block', marginRight: 20 }} key={item}>
                            <KbImage width={60} height={60} key={item} src={item} />
                          </div>
                        ))}
                        {showSendToPDDBtn ? (
                          <div>
                            <Button type='primary' onClick={() => passRecordToPDD(val.id)}>
                              提交该结果
                            </Button>
                          </div>
                        ) : null}
                      </>
                    }
                  />
                );
              })}
            </Steps>
          </Typography>
        ) : null}
        {status !== '1' && (
          <Typography style={{ marginBottom: 30 }}>
            <Title level={3}>工单处理</Title>
            <ProForm
              validateTrigger='onChange'
              onValuesChange={onValuesChange}
              onFinish={onSubmit}
              onReset={onReset}
              form={form}
              layout='horizontal'
              initialValues={{
                reason: complaint?.complaint_type_text,
                compensation: '1',
                compensationMoney: 0,
                files: imgList,
              }}
              submitter={{
                render: (props_) => {
                  return [
                    <Button
                      type='primary'
                      key='submit'
                      disabled={disableSubmit}
                      onClick={() => props_.form?.submit?.()}
                      loading={submitLoading}
                    >
                      提交
                    </Button>,
                  ];
                },
              }}
            >
              <ProForm.Group style={{ marginLeft: '10px' }}>
                <ProFormText readonly width='sm' name='reason' label='投诉原因' />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormSelect
                  fieldProps={{
                    onDropdownVisibleChange,
                  }}
                  width='sm'
                  name='select'
                  label='处理结果'
                  valueEnum={pddComplaintTypes}
                  placeholder='请选择处理结果'
                  rules={[{ required: true, message: '请选择处理结果' }]}
                />
              </ProForm.Group>

              <ProFormDependency name={['compensation', 'select']}>
                {({ compensation, select }) => {
                  const rules: Rule[] =
                    compensation === '2'
                      ? [
                          {
                            pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,
                            message: '赔偿金额需大于0',
                          },
                          { required: true },
                          { type: 'number' },
                        ]
                      : [{ type: 'number' }];
                  return pddComplaintTypes[select] === '包裹丢失' ? (
                    <ProForm.Group>
                      <ProFormSelect
                        allowClear={false}
                        rules={[{ required: true, message: '请选择是否需要赔偿' }]}
                        options={[
                          {
                            value: '1',
                            label: '无需赔偿',
                          },
                          {
                            value: '2',
                            label: '已赔付',
                          },
                        ]}
                        width='sm'
                        name='compensation'
                        label='是否赔偿'
                      />
                      <ProFormDigit
                        rules={rules}
                        label='赔偿金额（元）'
                        name='compensationMoney'
                        width='sm'
                        min={0}
                        disabled={compensation === '1'}
                        fieldProps={{ precision: 2 }}
                      />
                    </ProForm.Group>
                  ) : null;
                }}
              </ProFormDependency>
              <ProForm.Group {...tailLayout}>
                <ProFormTextArea
                  rules={[{ required: true, message: '请填写补充描述' }]}
                  allowClear
                  width='xl'
                  label='补充描述'
                  name='remark'
                  placeholder='请填写补充描述'
                />
              </ProForm.Group>

              <ProForm.Group>
                <ProFormUploadButton
                  fieldProps={{
                    onPreview,
                    beforeUpload,
                    fileList: imgList,
                    onRemove,
                  }}
                  rules={[{ required: true, message: '请上传凭证材料' }]}
                  accept='image/png, image/jpeg, image/jpg,'
                  max={5}
                  width='sm'
                  extra='扩展名仅限：png、jpg、jpeg，单张图片大小在600kb以内'
                  label='凭证材料'
                  name='files'
                  title='上传图片'
                  listType='picture'
                />
              </ProForm.Group>
            </ProForm>
          </Typography>
        )}
      </div>

      <div
        style={{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }}
      >
        <Button
          type='ghost'
          style={{ marginRight: 8 }}
          onClick={() => onNextOrPrevClick('prev')}
          disabled={!prevId}
        >
          上一工单
        </Button>
        <Button type='primary' onClick={() => onNextOrPrevClick('next')} disabled={!nextId}>
          下一工单
        </Button>
      </div>
    </Drawer>
  );
};

export default connect(
  ({ pddComplaint, loading }: ConnectState, { activeKey }: { activeKey: string }) => ({
    detail: pddComplaint.pddComplaintDetail,
    pddComplaintTypes: pddComplaint.pddComplaintTypes,
    page_ids: pddComplaint[`${activeKey}_page_ids`],
    loadingDetail: loading.effects['pddComplaint/getPddDetail'],
    submitLoading: loading.effects['pddComplaint/pddComplaintSubmit'],
  }),
)(React.memo(HandlingDrawerForm));
